package controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.JPAHiberDAOFactory;
import dao.entity.OrderDAO;
import dao.entity.OrderDetailDAO;
import dao.entity.ProductDAO;
import dao.entity.UserDAO;

import model.entity.OrderDetails;
import model.entity.OrderDetailsId;
import model.entity.Orders;
import model.entity.role.Users;

public class OrderContr extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    public OrderContr() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("here");
		String phone = request.getParameter("phone");
		String address = request.getParameter("address");
		String comment = request.getParameter("comment");
		
		HttpSession session = request.getSession();
		ArrayList<OrderDetails> cart = (ArrayList<OrderDetails>) session.getAttribute("cart");
		double moneySum = 0;
		for (OrderDetails orderDetails : cart) {
			moneySum += orderDetails.totalMoney();
		}
		
		String validationToken = Math.round(Math.random()*10000)+"";
		Users user = (Users) session.getAttribute("user");
		
		//Database
		UserDAO userDAO = JPAHiberDAOFactory.getInstance().getUserDAO();
		Orders orders = new Orders(phone, new Date(), false, false, moneySum, address, validationToken);
		orders.setUser(userDAO.findReference(user.getUserId()));
		orders.setComment(comment);
		
		OrderDAO orderDAO = new OrderDAO();
		orderDAO.persist(orders);
		
		//Chi tiet
		OrderDetailDAO detailDAO = new OrderDetailDAO();
		ProductDAO productDAO = JPAHiberDAOFactory.getInstance().getProductDAO();
		for (OrderDetails orderDetails : cart) {
			orderDetails.setProduct(productDAO.findReference(orderDetails.getProduct().getProductId()));
			orderDetails.setOrder(orders);
			orderDetails.setPriceAtSaleTime(orderDetails.getProduct().getPrice());
			
			OrderDetailsId id = new OrderDetailsId(orders.getOrderId(), orderDetails.getProduct().getProductId());
			orderDetails.setId(id);
			
			detailDAO.persist(orderDetails);
		}
		
		session.setAttribute("cart", null);
		session.setAttribute("token", validationToken);
		response.sendRedirect("shop/DanhSachSanPham.jsp");
	}

}
